% code to fit and visualize color clusters in the images
% load data
load('allData.mat');
vecImg = [];
for i = 1:4:length(dataCell)
	img = dataCell{i};
	img = imresize(img,0.25);
	vecImg= [vecImg; reshape(img,[],3)];
end
disp([ ' problem size: ' num2str(size(vecImg))]);
opts = statset('MaxIter',500);
model = gmdistribution.fit(im2double(vecImg),15,'Options',opts);
% visualize the EM model
[ Y, idx] = random(model,1e5);
for iModel = 1:model.NComponents
	% sample for the iModel-th component
	samples = Y(idx==iModel,:);
	% visualize it in the RGB space
	figure;
	scatter3(samples(:,1),samples(:,2),samples(:,3),5+zeros(size(samples,1),1),samples,'filled');
	% save to disk
	xlim([0 1]);
	ylim([0 1]);
	zlim([0 1]);
	xlabel('Red');
	ylabel('Greenn');
	zlabel('Blue');
	title(['component ' num2str(iModel) ' weight ' num2str(model.PComponents(iModel)) ] );
	view(-60,60);
	saveas(gcf,['mixture_' num2str(iModel) '_view1.pdf']);
	view(40,35);
	saveas(gcf,['mixture_' num2str(iModel) '_view2.pdf']);
	close;
end
figure;
hold on;
for iModel = 1:model.NComponents
	samples = Y(idx==iModel,:);
	scatter3(samples(:,1),samples(:,2),samples(:,3),5+zeros(size(samples,1),1), repmat(model.mu(iModel,:),size(samples,1),1),'filled');
end
saveas(gcf,['allMixture.pdf']);
close;

